import * as path from "path"
import * as fs from "fs";

export const projectDir = process.cwd()
export const uploadDir = path.join(projectDir, "environment", "uploadTemp"); // 指定上传目录
export const staticDir = path.join(projectDir, "environment", "public"); // 指定静态资源目录
export const videoProjectDir = path.join(projectDir, "environment", "public", "videoProjects"); // 指定交互视频目录

// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
}

// 确保静态资源目录存在
if (!fs.existsSync(staticDir)) {
    fs.mkdirSync(staticDir);
}
// 确保静态资源目录存在
if (!fs.existsSync(videoProjectDir)) {
    fs.mkdirSync(videoProjectDir);
}

export const deleteFolder = (path: string): void => {
    if (fs.existsSync(path)) {
        const files = fs.readdirSync(path);

        for (const file of files) {
            const curPath = path + '/' + file;

            if (fs.statSync(curPath).isDirectory()) { // 如果是子文件夹则递归调用自身
                deleteFolder(curPath);
            } else { // 否则直接删除文件
                fs.unlinkSync(curPath);
            }
        }

        fs.rmdirSync(path); // 最后删除空文件夹
    }
}

export const createFolder = (path: string): void => {
    if (fs.existsSync(path)) {
        fs.mkdirSync(path);
    }
}

export const existsSync = (path: string): boolean => {
    return fs.existsSync(path);
}

export const moveFile = async (sourcePath: string, targetPath: string) => {
    try {
        // 复制文件
        await fs.promises.rename(sourcePath, targetPath);
        // 删除原始文件
        // await fs.promises.unlink(sourcePath);
    } catch (err) {
        console.error('移动文件时发生错误:', err);
    }
}

export const deleteFile = async (targetPath: string) => {
    try {
        // 删除原始文件
        await fs.promises.unlink(targetPath);
    } catch (err) {
        console.error('删除文件时发生错误:', err);
    }
}